// 用户相关
import { defineStore } from "pinia";
import { reqLogin, requestUserInfo } from "@/api/user/index";
import type { loginForm, loginResponseData } from "@/api/user/type";
import type { UserState } from "./types/type";
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from "@/utils/token";
import { constantRoutes, asyncRoutes, anyRoutes } from "@/router/routes";
import router from "@/router";

/// 引入深拷贝
// @ts-ignore
import { cloneDeep } from "lodash";

/// 用于过滤当前用户需要展示的异步路由
function filterAsyncRoutes(asyncRoute: any, routes: any) {
    return asyncRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoutes(item.children, routes);
            }
            return true
        }
    })

}


/// 用户信息小仓库
let useUserStore = defineStore("User", {

    // 真正存储数据的地方
    state: (): UserState => {
        return {
            token: GET_TOKEN(),// 用户登录的token
            menuRoutes: constantRoutes, //存储生成菜单需要数组
            username: '',
            avatar: '',
            /// 存储按钮权限
            buttons: []
        }
    },

    actions: {
        /// 用户登录
        async userLogin(data: loginForm) {
            // 登录请求
            const result: loginResponseData = await reqLogin(data)
            if (result.code == 200) {
                this.token = (result.data.token as string)
                // 本地存储
                // localStorage.setItem('token', (result.data.token as string));
                SET_TOKEN((result.data.token as string))
                return 'Ok'
            } else {
                return Promise.reject(new Error(result.data.message))
            }
        },

        /// 获取用户信息
        async getUserInfo() {
            const result = await requestUserInfo();
            if (result.code == 200) {
                this.username = result.data.checkUser.username;
                this.avatar = result.data.checkUser.avatar;
                this.buttons = result.data.checkUser.buttons as string[];
                let userAsyncRoute = filterAsyncRoutes(cloneDeep(asyncRoutes), result.data.checkUser.routes);

                /// 路由器管理的只有常量路由，异步路由和任意路由没注册】
                [...userAsyncRoute, ...anyRoutes].forEach((item: any) => {
                    router.addRoute(item)
                })

                let allRouter = [...constantRoutes, ...userAsyncRoute, ...anyRoutes];
                // console.log('xx:::' + JSON.stringify(allRouter))
                this.menuRoutes = allRouter
                return 'Ok'
            } else {
                return Promise.reject('获取用户信息失败')
            }
        },

        /// 退出登录
        clearLogoInfo() {
            this.token = ''
            this.username = ''
            this.avatar = ''
            REMOVE_TOKEN()
        }
    }


});

export default useUserStore;